package com.globalwave.common;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.globalwave.common.cache.CodeHelper;
import com.globalwave.common.entity.VirtualGrid;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

public class GenCode {
	private Log log = LogFactory.getLog(GenCode.class) ;
	
	private VirtualGrid grid ;
	public GenCode(VirtualGrid grid) {
		this.grid = grid ;
	}
	
    public void generate() throws Exception {
        
        //定义数据  
        Map<String, Object> root = new HashMap<String, Object>();  
        root.put("g", grid);  
        VirtualGridExt e = new VirtualGridExt(grid) ;
        root.put("e", e);  
        
        Configuration cfg = new Configuration();  

        String dir = CodeHelper.getWebConfig("realPath");  
        log.debug(dir) ;
        
        //从什么地方加载freemarker模板文件  
        File templateDir = new File(dir + "../template") ;
        cfg.setDirectoryForTemplateLoading(templateDir);  
          
        //设置对象包装器  
        cfg.setObjectWrapper(new DefaultObjectWrapper());  
        cfg.setEncoding(Locale.CHINESE, "UTF-8") ;
          
        //设置异常处理器  
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);  
        
        
        

        Iterator<File> it = FileUtils.iterateFiles(templateDir, new String[]{"ftl"}, true) ;
		while (it.hasNext()) {
            File file = it.next() ;
            //log.debug(file.getPath().replace(templateDir.getPath(), "")) ;
            //log.debug(file.getName()) ;
            //log.debug(templateDir.isDirectory()) ;
            
            //genFile(ve, entity, file, file.getPath().replace(templateDir.getPath(), "")) ;
            //定义Template对象  
            cfg.setDirectoryForTemplateLoading(file.getParentFile());  
            Template template = cfg.getTemplate(file.getName(), Locale.CHINESE, "UTF-8");  
              
            //定义输出  
            String outputDir = file.getAbsolutePath() ;
            outputDir = outputDir.substring(outputDir.indexOf("template") + 8) ;
            outputDir = outputDir.replace("_Module_", e.getModuleName()) ;
            String outputName = dir + "../build" + outputDir ;
            outputName = outputName.substring(0, outputName.lastIndexOf(".")) ;
            outputName = outputName.replace("_Class_", e.getClassName()) ;
            FileUtils.forceMkdir(new File(outputName.substring(0, outputName.lastIndexOf(File.separator)))) ;
            
            OutputStreamWriter osw = new OutputStreamWriter(
            		new FileOutputStream(outputName), "UTF-8") ;
            PrintWriter out   
                = new PrintWriter(  
                    new BufferedWriter(  
                        //new FileWriter(dir+"../build/" + file.getName())  
                    	osw
                    )  
                );  
              
            //****最重要的就是这一步，动态加载“世界，你好”到abc所在的位置  
            template.process(root, out);  
            
            out.close() ;
            osw.close() ;
		}

        
    }
    


	public class VirtualGridExt {
		private VirtualGrid grid = null ;
		private String moduleName ;
		private String className ;
		private String entityName ;
		
		public VirtualGridExt(VirtualGrid grid) {
			this.grid = grid ;
		}

		public String getModuleName() {
			if (moduleName == null) {
				String[] codes = grid.getView().getCode_().split("\\.") ;
				if (codes == null || codes.length < 1) {
				    moduleName = grid.getView().getCode_() ;
				} else {
					moduleName = codes[0] ;
				}
			}
			return moduleName;
		}

		public void setModuleName(String moduleName) {
			this.moduleName = moduleName;
		}

		public String getClassName() {
			if (className == null) {
				className = grid.getEditForm().getView().getTable_name() ;
				className = className.substring(className.indexOf("_") + 1) ;
				className = className.toLowerCase() ;
				int i = -1 ;
				while ((i = className.indexOf("_"))>=0) {
					className = className.replaceFirst("_", "") ;
					if(i < className.length()) {
						className = className.substring(0, i) + 
						            className.substring(i, i + 1).toUpperCase() + 
						            className.substring(i + 1) ;
					}
				}
				className = className.substring(0, 1).toUpperCase() + className.substring(1) ;
			}
			return className;
		}

		public void setClassName(String className) {
			this.className = className;
		}

		public String getEntityName() {
			if (entityName == null) {
				String className = this.getClassName() ;
				entityName = className.substring(0, 1).toLowerCase() + className.substring(1) ;
			}
			return entityName;
		}

		public void setEntityName(String entityName) {
			this.entityName = entityName;
		}
		
		
	}
}
